import logging
import logging.handlers
import os
from config.log_config import LOG_CONFIG, get_log_file

def setup_logger(name):
    # 确保日志目录存在
    if not os.path.exists(LOG_CONFIG['LOG_DIR']):
        os.makedirs(LOG_CONFIG['LOG_DIR'])
    
    logger = logging.getLogger(name)
    logger.setLevel(getattr(logging, LOG_CONFIG['LOG_LEVEL']))

    # 避免重复添加处理器
    if not logger.handlers:
        # 创建文件处理器
        file_handler = logging.handlers.RotatingFileHandler(
            get_log_file(),
            maxBytes=LOG_CONFIG['LOG_FILE_MAX_BYTES'],
            backupCount=LOG_CONFIG['LOG_FILE_BACKUP_COUNT'],
            encoding=LOG_CONFIG['LOG_FILE_ENCODING']
        )
        file_handler.setLevel(getattr(logging, LOG_CONFIG['LOG_LEVEL']))

        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(getattr(logging, LOG_CONFIG['LOG_LEVEL']))

        # 设置格式
        formatter = logging.Formatter(
            LOG_CONFIG['LOG_FORMAT'], 
            LOG_CONFIG['DATE_FORMAT']
        )
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        # 添加处理器
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)

    return logger 